﻿using AutoMapper;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using SmartCity.BasicData.Api.Application.Commond.Login;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Repo.Innerface;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace SmartCity.BasicData.Api.Application.Handler.Login
{
    public class LoginHandler : IRequestHandler<LoginRequestCommand, ApiResult<AccountModel>>
    {
        private readonly IAccountRepo accountRepo;
        private readonly ILogRepo logRepo;
        private readonly ILogger<LoginHandler> logger;
        private readonly IMapper mapper;

        public LoginHandler(IAccountRepo accountRepo,ILogRepo logRepo,ILogger<LoginHandler> logger,IMapper mapper)
        {
            this.accountRepo = accountRepo;
            this.logRepo = logRepo;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
        public Task<ApiResult<AccountModel>> Handle(LoginRequestCommand request, CancellationToken cancellationToken)
        {

            //AccountModel accountModel = new AccountModel();
            //mapper.Map(request, accountModel);

            //mapper.Map<AccountModel>(request);


            ApiResult<AccountModel> result =new ApiResult<AccountModel>();

            var user = accountRepo.GetAsync(o=>o.AccountName==request.AccountName).Result.FirstOrDefault();
            if (user == null) {
                result.Msg = "账号不存在!";
            } else {
                if (user.AccountPass != request.AccountPass.GetMD5())
                {
                    result.Msg = "密码错误!";
                }
                else {
                    result = result.Sussess(user, "Bearer "+ CreateTokenString());
                }
            }

          return Task.FromResult(result);   
        }
    }
}
